#include "Image.h"
#include <fstream>


int Image::WriteToBitmap(const std::string filename)
{
	std::ofstream out(filename.c_str());
	
// construct the bmp file header
	bmpFileHeader head;
	head.b = 'B';
	head.m = 'M';
	int size_of_line = 3*width;
	size_of_line += (4-(size_of_line)%4)%4;
	head.size = size_of_line*height + sizeof(bmpFileHeader) + sizeof(DIBHeader);
	head.offset = 54;

//construct the DIB header	
	DIBHeader dib;
	dib.size = 40;
	dib.width = width;
	dib.height = height;
	dib.planes = 1;
	dib.bits_per_pixel = 24;
	dib.imageSize = head.size - 54;
	dib.hres = 2835;
	dib.vres = 2835;
	dib.numcolors = 0;
	dib.numimportantcolors = 0;
	dib.compression = 0;

	out.write((char*)&head,14);
	out.write((char*)&dib,40);
	int i,j;
	for (j = height-1; j >= 0; j--)
	{
		//output the line
		for (i = 0; i < width; i++)
		{
			Pixel loc = data[i+j*width];
			uint8_t pixout[3];
			loc.Map2Bmp(pixout);
			out << pixout[0] << pixout[1] << pixout[2];
		}
		//output padding 0's
		for (int k = 0; k < (4 - ((3*width)%4))%4; k++)
			out << '\0';
	}

	out.close();
	return 0;
}